<template>
    <!-- 搜索栏 -->
    <div class="bg">
        <div class="tip">
            <span class="line">|</span>
            查询用户
        </div>
        <span>用户名：</span>
        <el-input v-model="userName" style="width: 300px; margin-right:30px;"></el-input>
        <span>注册时间：</span>
        <el-date-picker v-model="time" type="daterange" range-separator="到" start-placeholder="开始日期"
            end-placeholder="结束日期" @change="changeTime" value-format="YYYY-MM-DD" />
        <el-button type="info" style="margin-left: 60px;" @click="reset">重置</el-button>
        <el-button type="primary" style="margin-left: 20px;" @click="search">查询</el-button>
    </div>
    <!-- 新增用户 -->
    <el-button type="primary" plain @click="openAddDialog">新增用户</el-button>
    <el-dialog v-model="AddUserVisible" width="500" title="新增用户" append-to-body align-center>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="adduserRules" label-width="80px" class="demo-ruleForm"
            status-icon>
            <el-form-item label="头像">
                <el-upload class="avatar-uploader" action="/oasadapi/users/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="用户名" prop="user_name">
                <el-input v-model="ruleForm.user_name" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password" type="password" show-password />
            </el-form-item>
            <el-form-item label="用户角色" prop="role">
                <el-select v-model="ruleForm.role" placeholder="请选择用户角色" style="width: 240px">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="enrollUser">
                    注册
                </el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <!-- 信息表格 -->
    <el-table :data="tableData" stripe style="width: 100%; margin-bottom:10px;">
        <!-- <el-table-column prop="id" label="ID" align="center" width="65" /> -->
        <el-table-column prop="user_avatar" label="用户头像" align="center">
            <template #default="scope">
                <el-avatar :size="45" fit="cover" :src="getImageUrl('avatar/' + scope.row.user_avatar)" />
            </template>
        </el-table-column>
        <el-table-column prop="user_name" label="用户名" align="center" />
        <el-table-column prop="role" label="角色" align="center" width="150">
            <template #default="scope">
                <el-tag type="warning" effect="dark" v-if="scope.row.role === 1">管理员</el-tag>
                <el-tag effect="dark" v-if="scope.row.role === 0">算法学习者</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="join_time" label="注册时间" align="center" />
        <el-table-column prop="email" label="邮箱" align="center">
            <template #default="scope">
                <el-text truncated>
                    {{ scope.row.email }}
                </el-text>
            </template>
        </el-table-column>
        <el-table-column label="签名" align="center">
            <template #default="scope">
                <el-text truncated>
                    {{ scope.row.motto }}
                </el-text>
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
            <template #default="scope">
                <el-popconfirm title="您确定要删除该用户吗?" @confirm="handleDelet(scope.row.id)">
                    <template #reference>
                        <el-button link type="primary" size="small">删除</el-button>
                    </template>
                </el-popconfirm>
                <el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination background layout="prev, ->,jumper,pager, next" :total="total" :page-size="7"
        v-model:current-page="currentPage" @current-change="changePage" />
    <!-- 修改用户信息dialog -->
    <el-dialog v-model="changeinfoVisible" width="500" title="修改用户信息" append-to-body align-center>
        <el-form ref="updateFormRef" :model="updateForm" :rules="rules" label-width="80px" class="demo-ruleForm"
            status-icon>
            <el-form-item label="头像:">
                <el-upload class="avatar-uploader" action="/oasadapi/users/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess2" :before-upload="beforeAvatarUpload2">
                    <img v-if="!imgFlag" :src="getImageUrl('avatar/' + imageUrl)" class="avatar" />
                    <img v-else :src="imageUrl" class="avatar" />
                </el-upload>
            </el-form-item>
            <el-form-item label="用户名:" prop="user_name">
                <el-input v-model="updateForm.user_name" disabled />
            </el-form-item>
            <el-form-item label="密码:" prop="password">
                <el-input v-model="updateForm.password" type="password" show-password />
            </el-form-item>
            <el-form-item label="邮箱:" prop="email">
                <el-input v-model="updateForm.email" />
            </el-form-item>
            <el-form-item label="签名:" prop="motto">
                <el-input v-model="updateForm.motto" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="changeinfoVisible = false">取消</el-button>
                <el-button type="primary" @click="handleUpdateConfirm">
                    确认
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import axios from "axios";
import { useUserStore } from "../../store/useUserStore.js";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'

const userStore = useUserStore();
const { user } = storeToRefs(userStore);

// 表格数据
let tableData = ref([]);
let allTableData = ref([]);
// 加载图片
const getImageUrl = (url: string) => {
    // 里面可以根据需求写逻辑
    return new URL('../../assets/' + url, import.meta.url).href;
};
// 分页器
let total = ref(7);
let currentPage = ref(1);
const changePage = () => {
    tableData.value = allTableData.value.slice((currentPage.value - 1) * 7, currentPage.value * 7);
}

// 初始化
onMounted(() => {
    search();
})

// 查询参数
let time = ref([]);
let userName = ref("");

// 日期选择器
const changeTime = () => {
    if (time.value && time.value.length) {
        startTime.value = time.value[0] + " 00:00:00";
        endTime.value = time.value[1] + " 23:59:59";
    } else {
        startTime.value = "";
        endTime.value = "";
    }
}
// 查询方法
const startTime = ref("");
const endTime = ref("");
const search = () => {
    axios.get(`/oasadapi/users/search`, { params: { user_name: userName.value, start_time: startTime.value, end_time: endTime.value } }).then((res) => {
        allTableData.value = res.data;
        tableData.value = res.data.slice((currentPage.value - 1) * 7, currentPage.value * 7);
        total.value = res.data.length;
    })
}
// 重置
const reset = () => {
    userName.value = "";
    time.value = [];
    startTime.value = "";
    endTime.value = "";
}

// 新增用户
let AddUserVisible = ref(false);
const openAddDialog = () => {
    AddUserVisible.value = true;
    imageUrl.value = "";
}
const imgFlag = ref(0);
const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    console.log(response);
    ruleForm.user_avatar = uploadFile.name;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('头像图片必须是JPG或者PNG格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('头像图片大小不能超过5MB!')
        return false
    }
    return true
}
const handleAvatarSuccess2: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    console.log(response);
    updateForm.user_avatar = uploadFile.name;
}

const beforeAvatarUpload2: UploadProps['beforeUpload'] = (rawFile) => {
    imgFlag.value = 1;
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('头像图片必须是JPG或者PNG格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('头像图片大小不能超过5MB!')
        return false
    }
    return true
}
const options = [
    {
        value: '0',
        label: '算法学习者',
    },
    {
        value: '1',
        label: '管理员',
    },
]
//获取表单对象
const ruleFormRef = ref()
const ruleForm = reactive({
    user_avatar: "",
    user_name: "",
    password: "",
    role: "",
})
const adduserRules = reactive({
    user_name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
})
const enrollUser = () => {
    ruleFormRef.value.validate(async (valid) => {
        if (valid) {
            await axios.post(`/oasadapi/users`, ruleForm).then((res) => {
                let { code, data } = res.data
                AddUserVisible.value = false
                if (code === 0) {
                    search();
                    ElMessage({
                        message: "注册成功！",
                        type: "success"
                    })
                    ruleForm.user_avatar = ""
                    ruleForm.user_name = ""
                    ruleForm.password = ""
                    ruleForm.role = "";
                    imageUrl.value = "";
                } else {
                    ElMessage.error("用户名已存在！")
                }
            })
        } else {
            ElMessage.error("注册失败！")
        }
    })
}

// 操作
const handleDelet = (id) => {
    axios.delete(`/oasadapi/users/${id}`).then(() => {
        search();
        ElMessage({
            message: "删除成功！",
            type: "success"
        })
    })
}
// 对话框
let changeinfoVisible = ref(false);
let userId = ref(0);
let changeUserValue = reactive({});
// 弹出修改个人信息框
const handleEdit = (data) => {
    changeinfoVisible.value = true;
    imgFlag.value = 0;
    imageUrl.value = data.user_avatar;
    updateForm.user_name = data.user_name;
    updateForm.password = data.password;
    updateForm.email = data.email;
    updateForm.motto = data.motto;
    userId = data.id;
    changeUserValue = data;
}
// 更新表单
const updateFormRef = ref()
const updateForm = reactive({
    user_avatar: "",
    user_name: "",
    password: "",
    email: "",
    motto: "",
})
const rules = reactive({
    user_name: [
        { message: '请输入用户名', trigger: 'blur' },
    ],
    password: [
        { message: '请输入密码', trigger: 'blur' },
    ],
    email: [
        { message: '请输入邮箱', trigger: 'blur' },
    ],
    motto: [
        { message: '请输入签名', trigger: 'blur' },
    ],
})

// 提交修改信息
const handleUpdateConfirm = async () => {
    changeinfoVisible.value = false;
    console.log(updateForm, changeUserValue);
    if (updateForm.user_avatar === changeUserValue.user_avatar && updateForm.password === changeUserValue.password && updateForm.email === changeUserValue.email && updateForm.motto === changeUserValue.motto) {
        ElMessage({
            message: "请先进行修改！",
            type: "warning"
        })
    } else
        await axios.put(`/oasadapi/users/${userId}`, updateForm).then((res) => {
            search();
            if (res.data.code === 0) {
                ElMessage({
                    message: "修改成功！",
                    type: "success"
                })
            } else {
                ElMessage({
                    message: "修改失败！",
                    type: "error"
                })
            }
        });
}

</script>

<style lang="scss" scoped>
.bg {
    background: #ecf5ff;
    padding: 50px;
    border-radius: 20px;
    margin-bottom: 20px;

    .tip {
        position: absolute;
        top: 30px;
        left: 30px;

        .line {
            width: 4px;
            height: 10px;
            background: #79bbff;
            color: #79bbff;
        }
    }

}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    text-align: center;
}

.avatar-uploader .avatar {
    width: 78px;
    height: 78px;
    display: block;
}
</style>